import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { getLocation } from '@/utils/location.js';
import { navigate } from '@/utils/navigate.js';
import ModalUtil from '@/utils/modal.js';
import { getKeepaliveIns } from '@/utils/keepaliveIns.js';
import { findRouteByAbsolutePath } from '@/router/fun.jsx';

// 记录上一次激活的路由
let lastActiveKey;

const useTabsStore = create(
  persist(
    (set, get) => ({
      // 激活的路由规则
      activeRouteRule: '',
      // 标签页列表 {url: "路由规则", title: "标题", "rule": "路由规则"}
      tabPages: [],
      // 获取标签页
      getTabPages: () => get().tabPages,
      // 设置标签页
      setTabPages: (update) => set({ tabPages: update(get().tabPages) }),
      // 添加标签页
      addTabPage: (tabPage) => set((state) => ({ tabPages: [...state.tabPages, tabPage] })),
      // 删除标签页
      removeTabPage: (url) =>
        set((state) => ({ tabPages: state.tabPages.filter((tab) => tab.url !== url) })),
      // 清空数据
      clear: () => {
        set({ tabPages: [], lastActiveKey: '' });
        getKeepaliveIns().destroyAll();
      },
      // 打开标签页
      openTabPage: (source, tabPage, options) => {
        const location = getLocation();
        const activeKey = location.pathname + location.search;
        const route = findRouteByAbsolutePath(activeKey);
        lastActiveKey = activeKey;
        const tabPages = get().tabPages;
        // 如果当前页已经在标签页列表中，则不处理
        if (!tabPages.some((tab) => tab.url === activeKey)) {
          // 没有子路由，说明不是一个布局页面
          if (route?.children === null || route?.children === undefined) {
            get().addTabPage(tabPage);
          }
        }
        // 如果当前页就是目标页，则不处理
        if (activeKey === tabPage.url) {
          return;
        }
        navigate(tabPage.url, {
          state: tabPage.state,
          ...options
        });
      },
      // 关闭标签页
      closeTabPage: (url) => {
        let tabPages = get().tabPages;
        const exist = tabPages.some((tab) => tab.url === url);
        if (!exist) {
          return;
        }
        if (tabPages.length <= 1) {
          ModalUtil.warn('无法关闭最后一个标签页');
          return;
        }
        getKeepaliveIns().destroy(url);
        tabPages = tabPages.filter((tab) => tab.url !== url);
        get().setTabPages(() => [...tabPages]);
        const tabPageFind = tabPages.find((tab) => tab.url === lastActiveKey);
        const nextActiveItem = tabPageFind || tabPages[tabPages.length - 1];
        navigate(nextActiveItem.url, {
          state: nextActiveItem.state,
          replace: true
        });
      }
    }),
    { name: 'tab', storage: createJSONStorage(() => sessionStorage) }
  )
);

export default useTabsStore;
